package com.dalongxin.work.page;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.baoyz.actionsheet.ActionSheet;
import com.dalongxin.work.Constants;
import com.dalongxin.work.EventCenter;
import com.dalongxin.work.R;
import com.dalongxin.work.data.Company;
import com.dalongxin.work.data.Contact;
import com.dalongxin.work.data.DjHtsp;
import com.dalongxin.work.data.Project;
import com.dalongxin.work.data.Supplier;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.view.MyCommonDialog;
import com.dalongxin.work.view.MyCommonEditDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 新建合同审批
 */
@ContentView(R.layout.activity_dj_new_htsp)
public class DjHtspNewActivity extends BaseActivity implements View.OnClickListener {

    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.submit)
    private TextView submit;

    @ViewInject(R.id.tv_choose_company)
    private TextView tvChooseCompany;//选择公司
    @ViewInject(R.id.tv_choose_shr)
    private TextView tvChooseShr;//选择审核人
    @ViewInject(R.id.tv_choose_pzr)
    private TextView tvChoosePzr;//选择批准人
    @ViewInject(R.id.et_htmc)
    private EditText etHtmc;//合同名称
    @ViewInject(R.id.et_htbh)
    private EditText etHtbh;//合同编号
    @ViewInject(R.id.et_htze)
    private EditText etHtze;//合同总额
    @ViewInject(R.id.tv_choose_yxq)
    private TextView tvChooseYxq;//有效期
    @ViewInject(R.id.tv_choose_sqrq)
    private TextView tvChooseSqrq;//申请日期
    @ViewInject(R.id.et_jhdd)
    private EditText etJhdd;//交货地点
    @ViewInject(R.id.et_wlmc)
    private EditText etWlmc;//物料名称
    @ViewInject(R.id.tv_choose_fplx)
    private TextView tvChooseFp;//发票类型
    @ViewInject(R.id.et_fkfs)
    private EditText etFkfs;//付款方式
    @ViewInject(R.id.tv_choose_xm)
    private TextView tvChooseXm;//选择项目
    @ViewInject(R.id.tv_choose_gys)
    private TextView tvChooseGys;//选择供应商
    @ViewInject(R.id.et_bz)
    private EditText etBz;//备注
    @ViewInject(R.id.btn_operate)
    private Button btnOperate;

    public static final int REQ_CHOOSE_COMPANY = 1001;
    public static final int REQ_CHOOSE_CONTACT_SHR = 1002;
    public static final int REQ_CHOOSE_CONTACT_PZR = 1003;
    public static final int REQ_CHOOSE_XM = 1004;
    public static final int REQ_CHOOSE_GYS = 1005;
    public Calendar calendar;

    private Company chooseCompany;
    private Contact chooseShr;
    private Contact choosePzr;
    private String yxq;
    private String sqrq;
    private String fplx;
    private Project chooseProject;
    private Supplier chooseSupplier;

    private String htmc;
    private String htbh;
    private String htze;
    private String jhdd;
    private String wlmc;
    private String fkfs;
    private String bz;

    private MyCommonDialog commonDialog;
    private MyCommonEditDialog commonEditDialog;

    public static final String IS_EDIT = "is_edit";
    private int isEdit = 0;// 0新建 1查看
    private DjHtsp bean;
    private boolean canEdit = false;
    private int editState = 0;//0查看状态 1修改状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        //this.setSupportActionBar(toolbar);//这样menu才能显示出来【自定义toolbar的话 这个不要设置】
        //getSupportActionBar().setDisplayShowTitleEnabled(false);//去掉默认title的显示
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        isEdit = getIntent().getIntExtra(IS_EDIT, 0);
        if(isEdit == 0) {
            titleText.setText("新建合同审批");
            submit.setText("提交");
            switchToEditState();
        }else {
            Bundle bundle = getIntent().getBundleExtra("bundle");
            bean = (DjHtsp) bundle.getSerializable("BEAN");
            if(bean == null) {
                finish();
                return;
            }
            if(bean.getCreateId() == getDefaultAccount().getId() && bean.getStatus() == 0) {
                canEdit = true;
                titleText.setText("查看合同审批");
                submit.setText("修改");
            }else {
                titleText.setText("查看合同审批");
                submit.setVisibility(View.GONE);
            }
            fillDataToPage(bean);
            btnOperate.setVisibility(showOperateBtn(bean) ? View.VISIBLE : View.GONE);
            btnOperate.setOnClickListener(this);
        }
        titleBack.setOnClickListener(this);
        submit.setOnClickListener(this);

        calendar = Calendar.getInstance();
    }

    private boolean showOperateBtn(DjHtsp bean) {
        if(bean.getStatus() == 0 && bean.getApproveId1() == getDefaultAccount().getId()) {
            return true;
        }
        if(bean.getStatus() == 1 && bean.getApproveId2() == getDefaultAccount().getId()) {
            return true;
        }
        return false;
    }

    private void fillDataToPage(DjHtsp bean) {
        chooseCompany = new Company();
        chooseCompany.setId(bean.getCompanyId());
        chooseCompany.setName(bean.getCompanyName());
        chooseShr = new Contact();
        chooseShr.setId(bean.getApproveId1());
        chooseShr.setUserName(bean.getApproveName1());
        choosePzr = new Contact();
        choosePzr.setId(bean.getApproveId2());
        choosePzr.setUserName(bean.getApproveName2());
        chooseProject = new Project();
        chooseProject.setId(bean.getProjectId());
        chooseProject.setName(bean.getProjectName());
        chooseSupplier = new Supplier();
        chooseSupplier.setId(bean.getSupplierId());
        chooseSupplier.setName(bean.getSupplierName());

        htmc = bean.getContractName();
        htbh = bean.getContractNumber();
        htze = String.valueOf(bean.getContractTotal());
        yxq = bean.getExpiryDate();
        sqrq = bean.getFillDate();
        jhdd = bean.getGoodsAddress();
        wlmc = bean.getGoodsName();
        fplx = String.valueOf(bean.getInvoiceType());
        if(bean.getInvoiceType() == 0) {
            tvChooseFp.setText("专票");
        }else if(bean.getInvoiceType() == 1) {
            tvChooseFp.setText("普票");
        }else {
            tvChooseFp.setText("其他");
        }
        fkfs = bean.getPayType();
        bz = bean.getRemark();

        tvChooseCompany.setText(chooseCompany.getName());
        tvChooseShr.setText(chooseShr.getUserName());
        tvChoosePzr.setText(choosePzr.getUserName());
        tvChooseXm.setText(chooseProject.getName());
        tvChooseGys.setText(chooseSupplier.getName());

        etHtmc.setText(htmc);
        etHtbh.setText(htbh);
        etHtze.setText(htze);
        tvChooseYxq.setText(yxq);
        tvChooseSqrq.setText(sqrq);
        etJhdd.setText(jhdd);
        etWlmc.setText(wlmc);
        etFkfs.setText(fkfs);
        etBz.setText(bz);

        switchToViewState();//默认查看状态
    }

    private void switchToEditState() {
        tvChooseCompany.setOnClickListener(this);
        tvChooseShr.setOnClickListener(this);
        tvChoosePzr.setOnClickListener(this);
        tvChooseYxq.setOnClickListener(this);
        tvChooseSqrq.setOnClickListener(this);
        tvChooseFp.setOnClickListener(this);
        tvChooseXm.setOnClickListener(this);
        tvChooseGys.setOnClickListener(this);
        etHtmc.setEnabled(true);
        etHtbh.setEnabled(true);
        etHtze.setEnabled(true);
        etJhdd.setEnabled(true);
        etWlmc.setEnabled(true);
        etFkfs.setEnabled(true);
        etBz.setEnabled(true);
    }

    private void switchToViewState() {
        tvChooseCompany.setOnClickListener(null);
        tvChooseShr.setOnClickListener(null);
        tvChoosePzr.setOnClickListener(null);
        tvChooseYxq.setOnClickListener(null);
        tvChooseSqrq.setOnClickListener(null);
        tvChooseFp.setOnClickListener(null);
        tvChooseXm.setOnClickListener(null);
        tvChooseGys.setOnClickListener(null);
        etHtmc.setEnabled(false);
        etHtbh.setEnabled(false);
        etHtze.setEnabled(false);
        etJhdd.setEnabled(false);
        etWlmc.setEnabled(false);
        etFkfs.setEnabled(false);
        etBz.setEnabled(false);
    }

    private void submitHtsp() {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("approveId1", String.valueOf(chooseShr.getId()));
        params.put("approveId2",String.valueOf(choosePzr.getId()));
        params.put("companyId", String.valueOf(chooseCompany.getId()));
        params.put("contractName", htmc);
        params.put("contractNumber", htbh);
        params.put("contractTotal", htze);
        params.put("expiryDate", yxq);
        params.put("fillDate", sqrq);
        params.put("goodsAddress", jhdd);
        params.put("goodsName", wlmc);
        params.put("invoiceType", fplx);
        params.put("payType", fkfs);
        params.put("projectId", String.valueOf(chooseProject.getId()));
        params.put("supplierId", String.valueOf(chooseSupplier.getId()));
        params.put("remark", bz);
        if(canEdit) {
            params.put("id", String.valueOf(bean.getId()));
        }else {
            params.put("id", String.valueOf(0));
        }
        HttpUtil.getInstance().post(true, Constants.url_saveContract, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.HTSP_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void submitApprove(String content, int result) {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("msg", content);
        params.put("result", String.valueOf(result));
        params.put("id", String.valueOf(bean.getId()));
        HttpUtil.getInstance().post(true, Constants.url_approveContract, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                commonEditDialog.dismiss();
                LogUtil.e("response=" + response);
                if (response.optInt("ret") == 0) {
                    ToastUtil.showShort("提交成功");
                    EventBus.getDefault().post(EventCenter.call(EventCenter.HTSP_REFRESH));
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showShort("服务器返回失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void preSubmit() {
        if(chooseCompany == null) {
            ToastUtil.showShort("请选择公司");
            return;
        }
        if(chooseShr == null) {
            ToastUtil.showShort("请选择审核人");
            return;
        }
        if(choosePzr == null) {
            ToastUtil.showShort("请选择批准人");
            return;
        }
        htmc = etHtmc.getText().toString();
        if(TextUtils.isEmpty(htmc)) {
            ToastUtil.showShort("请填写合同名称");
            return;
        }
        htbh = etHtbh.getText().toString();
        if(TextUtils.isEmpty(htbh)) {
            ToastUtil.showShort("请填写合同编号");
            return;
        }
        htze = etHtze.getText().toString();
        if(TextUtils.isEmpty(htze)) {
            ToastUtil.showShort("请填写合同总额");
            return;
        }
        if(TextUtils.isEmpty(yxq)) {
            ToastUtil.showShort("请选择有效期");
            return;
        }
        if(TextUtils.isEmpty(sqrq)) {
            ToastUtil.showShort("请选择申请日期");
            return;
        }
        jhdd = etJhdd.getText().toString();
        if(TextUtils.isEmpty(jhdd)) {
            ToastUtil.showShort("请填写交货地点");
            return;
        }
        wlmc = etWlmc.getText().toString();
        if(TextUtils.isEmpty(wlmc)) {
            ToastUtil.showShort("请填写物料名称");
            return;
        }
        if(TextUtils.isEmpty(fplx)) {
            ToastUtil.showShort("请选择发票类型");
            return;
        }
        fkfs = etFkfs.getText().toString();
        if(TextUtils.isEmpty(fkfs)) {
            ToastUtil.showShort("请填写付款方式");
            return;
        }
        if(chooseProject == null) {
            ToastUtil.showShort("请选择项目");
            return;
        }
        if(chooseSupplier == null) {
            ToastUtil.showShort("请选择供应商");
            return;
        }
        bz = etBz.getText().toString();
        if(TextUtils.isEmpty(bz)) {
            bz = "";
        }
        commonDialog = new MyCommonDialog(this, "提示消息", "确定提交吗？", "检查一下","提交");
        commonDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
                submitHtsp();
            }
        });
        commonDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null && commonDialog.isShowing())
                    commonDialog.dismiss();
            }
        });
        commonDialog.show();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.submit:
                if(isEdit == 0) {
                    preSubmit();
                }else {
                    if(canEdit) {
                        if (editState == 0) {
                            editState = 1;
                            titleText.setText("修改合同审批");
                            submit.setText("提交");
                            switchToEditState();
                        } else {
                            editState = 0;
                            titleText.setText("修改合同审批");
                            preSubmit();
                        }
                    }
                }
                break;
            case R.id.tv_choose_yxq:
                int year1 = calendar.get(Calendar.YEAR);
                int month1 = (calendar.get(Calendar.MONTH))+1;
                int day_of_month1 = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        yxq = String.format("%d-%d-%d",i,i1+1,i2);
                        tvChooseYxq.setText(yxq);
                        tvChooseYxq.setTextColor(getResources().getColor(R.color.black));
                    }
                },year1, month1, day_of_month1).show();
                break;
            case R.id.tv_choose_sqrq:
                int year2 = calendar.get(Calendar.YEAR);
                int month2 = (calendar.get(Calendar.MONTH))+1;
                int day_of_month2 = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        sqrq = String.format("%d-%d-%d",i,i1+1,i2);
                        tvChooseSqrq.setText(sqrq);
                        tvChooseSqrq.setTextColor(getResources().getColor(R.color.black));
                    }
                },year2, month2, day_of_month2).show();
                break;
            case R.id.tv_choose_fplx:
                ActionSheet.createBuilder(this, getSupportFragmentManager())
                        .setCancelButtonTitle("取消")
                        .setOtherButtonTitles("专票", "普票", "其他")
                        .setCancelableOnTouchOutside(true)
                        .setListener(new ActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                            }
                            @Override
                            public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                                String fplxStr = "";
                                switch (index) {
                                    case 0:
                                        fplxStr = "专票";
                                        break;
                                    case 1:
                                        fplxStr = "普票";
                                        break;
                                    case 2:
                                        fplxStr = "其他";
                                        break;
                                }
                                fplx = String.valueOf(index);
                                tvChooseFp.setText(fplxStr);
                                tvChooseFp.setTextColor(getResources().getColor(R.color.black));
                            }
                        }).show();
                break;
            case R.id.tv_choose_company:
                intent = new Intent(this, CompanyListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_COMPANY);
                break;
            case R.id.tv_choose_shr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_SHR);
                break;
            case R.id.tv_choose_pzr:
                intent = new Intent(this, ContactListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_CONTACT_PZR);
                break;
            case R.id.tv_choose_xm:
                intent = new Intent(this, ProjectListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_XM);
                break;
            case R.id.tv_choose_gys:
                intent = new Intent(this, SupplierListActivity.class);
                startActivityForResult(intent, REQ_CHOOSE_GYS);
                break;
            case R.id.btn_operate:
                final MyCommonEditDialog.Builder builder2 = new MyCommonEditDialog.Builder(this);
                commonEditDialog = builder2.view(R.layout.dialog_approve).widthdp(300).heightdp(320).style(R.style.MyDialogStyle)
                        .addViewOnclick(R.id.cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                commonEditDialog.dismiss();
                            }
                        }).addViewOnclick(R.id.ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                EditText etSpyj = (EditText)builder2.findViewById(R.id.et_spyj);
                                String spyj = etSpyj.getText().toString();
                                if(TextUtils.isEmpty(spyj)) {
                                    spyj = "";
                                }
                                RadioButton yes = (RadioButton)builder2.findViewById(R.id.radio_result_yes);
                                submitApprove(spyj, yes.isChecked() ? 0 : 1);
                            }
                        }).build();
                commonEditDialog.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null)return;
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_CHOOSE_COMPANY:
                    chooseCompany = (Company)data.getSerializableExtra(CompanyListActivity.DATA_CHOOSE_COMPANY);
                    tvChooseCompany.setText(chooseCompany.getName());
                    tvChooseCompany.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_SHR:
                    //Department department = (Department)data.getSerializableExtra(DepartmentListActivity.DATA_CHOOSE_DEPARTMENT);
                    chooseShr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChooseShr.setText(chooseShr.getUserName());
                    tvChooseShr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_CONTACT_PZR:
                    choosePzr = (Contact)data.getSerializableExtra(ContactListActivity.DATA_CHOOSE_CONTACT);
                    tvChoosePzr.setText(choosePzr.getUserName());
                    tvChoosePzr.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_XM:
                    chooseProject = (Project)data.getSerializableExtra(ProjectListActivity.DATA_CHOOSE_XM);
                    tvChooseXm.setText(chooseProject.getName());
                    tvChooseXm.setTextColor(getResources().getColor(R.color.black));
                    break;
                case REQ_CHOOSE_GYS:
                    chooseSupplier = (Supplier)data.getSerializableExtra(SupplierListActivity.DATA_CHOOSE_GYS);
                    tvChooseGys.setText(chooseSupplier.getName());
                    tvChooseGys.setTextColor(getResources().getColor(R.color.black));
                    break;
            }
        }
    }
}
